<?php
namespace backend\service ;

use Yii;
use backend\models\AdminUser;
use yii\db\Query ;
use yii\data\Pagination ;
use common\models\AuthItem;
use common\service\BaseToolService;
use common\service\MessageService;

class AdminUserService {
    /**
     * 后台管理员列表
     * @param $model
     *
     * @return array
     */
    public static function getAdminUserList($model){
        $admin_user_table_name = AdminUser::tableName();
        $query = new Query();
        $pages = null;
        $limit = 20;
        $query->select("*")
            ->from($admin_user_table_name)
            ->orderBy("user_id desc");

        //过滤admin
        $admin = !empty(Yii::$app->admin->identity->username)?Yii::$app->admin->identity->username:'';
        if ($admin != 'admin') {
            $query->andWhere(['!=', 'username', 'admin']);
        }

        //过滤真实姓名
        if (isset($model['realname']) && !empty($model['realname'])) {
            $query->andWhere(['like','realname',$model['realname']]);
        }
        //过滤工号
        if (isset($model['username']) && !empty($model['username'])) {
            $query->andWhere(['like','username',$model['username']]);
        }
        //过滤手机
        if (isset($model['phone']) && !empty($model['phone'])) {
            $query->andWhere(['like','phone',$model['phone']]);
        }
        //过滤角色
        if (isset($model['role']) && !empty($model['role'])) {
            $query->andWhere(['like','role',$model['role']]);
        }
        //过滤账户状态
        if (isset($model['status']) && $model['status'] != '') {
            $query->andWhere(['status'=>$model['status']]);
        }

        //过滤所属门店
        if (!empty($model['store_code']) && $model['store_code'] != '-1') {
            $query->andWhere(['store_code'=>$model['store_code']]);
        }

        if (isset($limit)) {
            $pages = new Pagination(['totalCount' => $query->count(), 'defaultPageSize' => $limit]);
            $query->offset($pages->offset)
                ->limit($limit);
        }

        $list = $query->all();

        $role = AuthItem::find()->andWhere(['type'=>1])->asArray()->all();
        $role_arr = [''=>'全部'];
        foreach($role as $value){
            $role_arr[$value['name']] = $value['name'];
        }

        return ['model'=>$model, 'list'=>$list, 'pages'=>$pages, 'role'=>$role_arr];
    }

    /**
     * 密码重置后发送到用户邮箱
     * @param $model
     *
     * @return array
     */
    public static function resetPasswords($model){
        $new_password = self::generatePassword();

        $user = AdminUser::findOne(["user_id" => $model->user_id]);
        if (empty($user)) {
            return ["status" => false, "msg" => "无此用户"];
        }

        $en_password = BaseToolService::encodePassword($user->password_order, $new_password);
        $user->password = $en_password;
        $user->paypassword = $en_password;
        $user->uptime = time() ;
        $user->upip = Yii::$app->getRequest()->userIP ;
        $add_rs = $user->save() ;
        if(!$add_rs){
            return ["status" => false, "msg" => "重置失败"];
        }

        $user_info = \common\models\AdminUser::findOne(['user_id'=>$model->user_id]);
//        $mail = \Yii::$app->mailer->compose()
//            ->setTo($user_info->email)
//            ->setSubject('密码重置')
//            ->setHtmlBody('<br>你的团贷联盟后台登录密码已重置，新密码为'.$new_password.'。')
//            ->send();
        $mail = MessageService::sendBackendResetPwd($new_password, $user->email);
        if($mail['code'] != 200){
            return ["status" => false, "msg" => "操作失败，邮件格式不正确或发送失败"];
        }
        return ["status" => true, "msg" => "操作成功，新密码已发送到该用户邮箱"];
    }

    /**
     * 生成指定规则密码
     * @param int $length
     *
     * @return string
     */
    public static function generatePassword( $length = 8 ) {
        // 密码字符集，可任意添加你需要的字符
        $chars = 'abcdefghijklmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ0123456789';

        $password = '';
        for ( $i = 0; $i < $length; $i++ )
        {
            // 这里提供两种字符获取方式
            // 第一种是使用 substr 截取$chars中的任意一位字符；
            // 第二种是取字符数组 $chars 的任意元素
            // $password .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
            $password .= $chars[ mt_rand(0, strlen($chars) - 1) ];
        }

        return $password;
    }

    /**
     * 获取用户
     * @return array
     */
    public static function getUser($typeId=null){
        $query = new Query();
        $pages = null;

        $query->select("*")
            ->from(AdminUser::tableName())
            ->orderBy("user_id asc") ;

        if(!empty($typeId)){
            $query->where(["type_id"=>$typeId]) ;
        }

        $users = $query->all();

        return $users ;
    }
}
